import { reactive, toRefs, computed, inject, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { voteApi } from '@/api'
export default props => {
    const router = useRouter()
    const params = reactive({
        voteInfo: null,
        hasVoteInfo: computed(() => !!params.voteInfo),
        voting: computed(() => {
            let flag = false
            if (params.hasVoteInfo) {
                flag = params.voteInfo.endtime * 1000 > new Date().getTime()
            }
            return flag
        }),
        themeColor: inject('themeColor'),
        maxCnt: null,
        voteBtnDisabledColor: '#e5e9ef',        
        selectedVoteOptions: computed(() => {
            let arr = []
            if (params.hasVoteInfo) {
                arr = params.voteInfo.options.filter(item => item.checked)
            }
            return arr
        }),
        hasVoteResult: computed(() => params.selectedVoteOptions.length > 0)
    })

    const getInfo = async () => {
        try {
          const { data } = await voteApi.getInfo({
            vote_id: props.vid
          })
          const { info, info: { cnt, options, uid } } = data
          if (uid === 0) {
            throw new Error('没有用户信息')
          }
  
          const cnts = []
          options.forEach(option => {
            if (option.cnt) {
              cnts.push(option.cnt)
              option.percentage = (option.cnt / cnt * 100).toFixed(2) + '%'
            } else {
              option.percentage = '0.00%'
            }
            option.checked = false
          })
          if (cnts.length) {
            params.maxCnt = Math.max(...cnts)
          }
          params.voteInfo = info
        } catch (error) {
          throw new Error(error)
        }
    }
  

    const leftTime = value => {
        const endtime = value * 1000
        const nowtime = new Date().getTime()
        const left = endtime - nowtime
        if (left >= 0) {
          const leftDay = Number.parseInt(left / (24 * 60 * 60 * 1000))
          const leavel = left % (24 * 3600 * 1000)
          const leftHours = Math.floor(leavel / (3600 * 1000))
          const leavel2 = leavel % (3600 * 1000)
          const leftMinutes = Math.floor(leavel2 / (60 * 1000))
          return `剩余${leftDay}天${leftHours}时${leftMinutes}分`
        }
    }

    const handleSpace = mid => {
        router.push({
          name: 'space',
          params: {
            mid
          }
        })
    }

    const handleCheck = item => {
        const { idx, checked } = item
        const { choice_cnt, options } = params.voteInfo
        if (!checked && params.selectedVoteOptions.length === choice_cnt) {
            Toast(`最多只能选择${choice_cnt}项`)
            return
        }
        const matchOption = options.find(option => option.idx === idx)
        matchOption.checked = !checked      
    }

    const handleVote = () => {
        Toast('功能开发中...')
    }

    watch(() => props.vid, () => {
        getInfo()
    }, {
        immediate: true
    })

    return {
        ...toRefs(params),
        leftTime,
        handleSpace,
        handleCheck,
        handleVote
    }
}